#!/usr/bin/env node

var package_common = require("./packages/enoad-common/package.json");
var package_component = require("./packages/enoad-component/package.json");
var package_web = require("./packages/enoad-component-web/package.json");
var versionMap = {};
for (var key in package_common) {
  if (key == "version") {
    versionMap["enoad-common"] = package_common["version"];
    break;
  }
}
for (var key in package_component) {
  if (key == "version") {
    versionMap["enoad-component"] = package_component["version"];
    break;
  }
}
for (var key in package_web) {
  if (key == "version") {
    versionMap["enoad-component-web"] = package_web["version"];
    break;
  }
}
upgradeFile(versionMap);

function upgradeFile(versionMap) {
  console.log("\033[42;30m START \033[40;32m 切换enoad-common,enoad-component,enoad-component-web的版本\033[0m");
  console.info(versionMap);
  var package_example = "./packages/example/package.json";
  var fs = require("fs");
  fs.readFile(package_example, "utf8", function (err, data) {
    let data_ = JSON.parse(data);
    let dependencies = data_.dependencies;
    let isChanged = false;
    if (dependencies["enoad-common"] != versionMap["enoad-common"]) {
      dependencies["enoad-common"] = versionMap["enoad-common"];
      isChanged = true;
    }
    if (
      dependencies["enoad-component"] != versionMap["enoad-component"]
    ) {
      dependencies["enoad-component"] = versionMap["enoad-component"];
      isChanged = true;
    }
    if (
      dependencies["enoad-component-web"] != versionMap["enoad-component-web"]
    ) {
      dependencies["enoad-component-web"] = versionMap["enoad-component-web"];
      isChanged = true;
    }
    const res_json = JSON.stringify(data_, null, 2);
    isChanged &&
      fs.writeFile(package_example, res_json, "utf8", function (err) {
        if (err) return console.log(err);
      });
    console.log("\033[42;30m DONE \033[40;32m Changed successfully\033[0m");
  });
}
